import { Component } from "react"
import ReactReduxContext from './ReactReduxContext';
/**
 * 连接组件和仓库
 * @param {*} mapStateToProps 
 * @param {*} mapDispatchToProps 
 * @returns 
 */
export default function connect ( mapStateToProps, mapDispatchToProps ) {
  return ( OldComponent ) => {
    return class extends Component {
      static contextType = ReactReduxContext; // 注入store实例
      constructor ( props, context ) {
        super( props )
        // 解析store实例
        let { store: { getState, subscribe, dispatch } } = context
        this.state = mapStateToProps( getState() );

        // 订阅，dispatch执行会触发订阅器，触发更新
        this.unsubscribe = subscribe( () => {
          this.setState( mapStateToProps( getState() ) );
        } )
        let dispatchProps;
        if ( typeof mapDispatchToProps === 'function' ) {
          // 执行注入dispatch
          dispatchProps = mapDispatchToProps( dispatch )
        } else {
          dispatchProps = {}
          // 将action动作，转换成dispatch能触发的动作
          for ( const key in mapDispatchToProps ) {
            dispatchProps[ key ] = () => dispatch( mapDispatchToProps[ key ]() )
          }
        }
        
        this.dispatchProps = dispatchProps
      }

      // 组件销毁时取消订阅
      componentWillUnmount () {
        this.unsubscribe();
      }
      render () {
        return <OldComponent {...this.props}  {...this.state} {...this.dispatchProps}></OldComponent>
      }
    }
  }
}